import { _decorator, Component, Node, Sprite, Color, math } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CooldownComponent')
export class CooldownComponent extends Component {
    @property(Node)
    cdNode: Node = null;

    @property(Sprite)
    cdSprite: Sprite = null;

    @property
    fadeEffect: boolean = true; // 是否启用透明度渐变效果

    private _originalColor: Color = null;
    private _isCooling: boolean = false;
    private _currentTime: number = 0;
    private _totalTime: number = 0;

    start() {
        if (this.cdSprite) {
            this._originalColor = this.cdSprite.color.clone();
            this.cdSprite.fillRange = 1;
            this.cdNode.active = false;
        }
    }

    /**
     * 开始CD
     * @param duration CD时长
     */
    public startCooldown(duration: number) {
        this._isCooling = true;
        this._currentTime = duration;
        this._totalTime = duration;
        
        if (this.cdNode) {
            this.cdNode.active = true;
            this.cdSprite.fillRange = 1;
        }
    }

    /**
     * 停止CD
     */
    public stopCooldown() {
        this._isCooling = false;
        this._currentTime = 0;
        
        if (this.cdNode) {
            this.cdNode.active = false;
        }
    }

    /**
     * 获取当前CD状态
     */
    public get isCooling(): boolean {
        return this._isCooling;
    }

    update(deltaTime: number) {
        if (!this._isCooling || !this.cdSprite) return;

        this._currentTime -= deltaTime;
        
        if (this._currentTime <= 0) {
            this.stopCooldown();
            return;
        }

        // 更新填充比例
        const progress = 1 - (this._currentTime / this._totalTime);
        this.cdSprite.fillRange = progress;

        // 更新颜色透明度
        if (this.fadeEffect && this._originalColor) {
            const color = new Color(
                this._originalColor.r,
                this._originalColor.g,
                this._originalColor.b,
                math.lerp(255, 100, progress)
            );
            this.cdSprite.color = color;
        }
    }
} 